<template>
  <div class="consultation">
    <h2>书法家管理</h2>
    <div class="consultation-block">
      <el-button type="primary" size="mini" @click="openDialog('add')">新增</el-button>
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="书法家名称"> </el-table-column>
          <el-table-column label="书法家图片">
            <template slot-scope="scope">
              <el-image 
                v-if="scope.row.img"
                style="width: 100px; height: 100px"
                :src="scope.row.img" 
                :preview-src-list="[scope.row.img]">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="text" label="书法家描述"> </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                v-if="scope.row.name !== 'admin'"
                @click="openDialog('edit', scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                v-if="scope.row.name !== 'admin'"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="form"
        size="mini"
        label-width="120px"
        class="demo-form"
      >
        <el-form-item label="书法家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="书法家图片" prop="img">
          <div class="img-blocks">
            <div
              v-if="form.img"
              style="position: relative"
            >
              <img :src="form.img" style="width: 80px" />
              <i @click="deleteImg()" class="el-icon-circle-close"></i>
            </div>
          </div>
          <el-upload
            v-if="!form.img"
            class="avatar-uploader"
            :action="'/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="书法家描述" prop="text">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            v-model="form.text">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSFJ, addSFJ, updateSFJ, deleteSFJ } from "../service.js";
export default {
  name: "home",
  mounted() {
    this.refreshTable();
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {},
      price: 0,
      roleOption: [
        {
          key: 'sadmin',
          value: '超级管理员'
        },
        {
          key: 'admin',
          value: '普通管理员'
        }
      ],
      rules: {
        password: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
      }
    };
  },
  methods: {
    handleAvatarSuccess(info) {
      this.form.img.push(info.url);
    },
    openDialog(type, row = {}) {
      if (type === 'add') {
        this.dialogTitle = "添加";
        this.form = {
          name: '',
          img: '',
          text: ''
        };
      } else {
        this.dialogTitle = "编辑";
        this.form = JSON.parse(JSON.stringify(row));
        console.log(this.form)
      }
      this.isVisible = true;
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.currentPage = index
      this.refreshTable()
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "添加") {
            addSFJ({
              ...this.form,
            }).then(res => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.refreshTable();
                this.isVisible = false;
              } else {
                this.$message.error(res.msg || '操作失败');
              }
            })
            return
          }
          updateSFJ(this.form.id, {
            ...this.form
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("操作成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    addData() {
      this.dialogTitle = "新增";
      this.isVisible = true;
    },
    refreshTable() {
      getSFJ({
        page: this.currentPage,
        pageSize: this.pageSize
      }).then((res) => {
        this.tableData = res.code === 200 && res.data ? res.data : [];
        this.total = res.data.total || 0
      });
    },
    updateData(row) {
      this.form = {
        ...row
      };
      this.dialogTitle = "修改";
      this.isVisible = true;
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteSFJ(row.id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteImg() {
      this.form.img = '';
    },
    handleAvatarSuccess(info) {
      console.log(this.form.img)
      this.form.img = info.url;
      console.log(this.form.img)
    },
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
</style>
